﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using FixEngine.Configuration;
using System.Configuration;

namespace FixEngine
{
    public class MessageFactory
    {
        static Dictionary<string,Type> _table = null;
        static MessageFactory()
        {
            if (_table == null)
            {
                _table = new Dictionary<string, Type>();
                //Type[] types = Assembly.GetExecutingAssembly().GetTypes();
                FixLibrarySection section = (FixLibrarySection)ConfigurationManager.GetSection("fixLibrarySection");
                foreach (FixLibrary lib in section.List)
                {
                    Type[] types = Assembly.Load(lib.AssemblyName).GetTypes();
                    foreach (Type type in types)
                    {
                        if (type.IsAbstract || type.IsInterface)
                            continue;

                        Type iField = type.GetInterface(typeof(IMessage).FullName, true);
                        if (iField != null)
                        {
                            IMessage instance = (IMessage)Activator.CreateInstance(type);
                            string key = string.Format("{0}{1}", instance.Version.ToString(), instance.MessageType);
                            if (!_table.ContainsKey(key))
                            {
                                _table.Add(key, type);
                            }
                        }
                    }
                }
            }
        }
        public static IMessage CreateMessage(FixVersion ver,string msgtype)
        {
            string key = string.Format("{0}{1}", ver.ToString(), msgtype);
            if (!_table.ContainsKey(key))
                throw new FixEngineException("Message class or assembly not found");
            Type type = _table[key];
            IMessage newInstance = (IMessage)Activator.CreateInstance(type);
            return newInstance;
        }
    }
}
